package com.example.edu_msm.controller;

import com.example.commonutils.R;
import com.example.edu_msm.service.MsmService;
import com.example.edu_msm.utils.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

/**
 * @author LUOXIN
 * @create 2021-09-15 14:40
 */
@RestController
@RequestMapping("edu_msm/msm")

public class MsmController {
    @Autowired
    private MsmService msmService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @GetMapping("send/{phone}")
    public R sendMsm(@PathVariable String phone){
        //1从redis获取验证码，如果有直接返回
        String code = redisTemplate.opsForValue().get(phone);
        if (StringUtils.hasLength(code)){
            return R.ok();
        }

        //获取不到进行阿里云发送
        code = RandomUtils.getSixBitRandom();
        HashMap<String, Object> param = new HashMap<>();
        param.put("code",code);

        boolean isSend=msmService.send(param,phone);

        if (isSend){
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
            return R.ok();
        }else {
            return R.error().message("短信发送失败");
        }
    }
}
